//
//  DQMainViewController.swift
//  DouQu
//
//  Created by guojianfeng on 2017/7/25.
//  Copyright © 2017年 guojianfeng. All rights reserved.
//

import UIKit

class DQMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

extension DQMainViewController{
    fileprivate func setupChildControllers(){
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = docDir.appending("/main.json")
        var fileData = try? Data.init(contentsOf: URL.init(fileURLWithPath: jsonPath))
        
        if fileData == nil {
            guard let path  = Bundle.main.path(forResource: "main.json", ofType: nil) else{
                return
            }
            fileData = try! Data.init(contentsOf: URL.init(fileURLWithPath: path))
        }
        guard let arr = try? JSONSerialization.jsonObject(with: fileData! , options: []) as? [[String: AnyObject]]
            else{
                return
        }
        
        var arrayM = [UIViewController]()
        for dict in arr! {
            arrayM.append(controller(dict as [String : AnyObject]))
        }
        viewControllers = arrayM
    }
    
    fileprivate func controller(_ dict: [String: AnyObject]) -> UIViewController{
        guard let clsName = dict["className"],
            let title = dict["title"],
            let imageName = dict["imageName"],
            let cls = NSClassFromString(Bundle.main.nameSpace + "." + (clsName as! String)) as? UIViewController.Type
            else{
                return UIViewController()
        }
        
        let vc: DQBaseViewController = cls.init() as! DQBaseViewController
        vc.title = title as? String
        vc.tabBarItem.image = UIImage.init(named: "tabBar_" + (imageName as! String))
        vc.tabBarItem.selectedImage = UIImage.init(named: "tabBar_" + (imageName as! String) + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: .normal)
        let nav = DQBaseNavgationController(rootViewController: vc)
        return nav
    }
}
